package com.mystudio.android.calendar.adaptor;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.text.format.Time;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.mystudio.android.calendar.constants.Constants;
import com.mystudio.android.calendar.model.Calendar;
import com.mystudio.android.calendar.model.CalendarConfig;
import com.mystudio.android.calendar.model.Instance;
import com.mystudio.android.calendar.util.CPSyncUtil;
import com.mystudio.android.calendar.view.WeekInMonthView;
import com.mystudio.android.util.Logger;

/**
 * Position here refers to the number of weeks count from the week of 0 Julian day (assume week start from Sunday)  
 */
public class CalendarAdapter extends BaseAdapter {
	private static final Logger logger = new Logger(Constants.LOG_TAG, CPSyncUtil.class);
	private static final int MAX_POSITION = 767640;  // should already covers to year 9999
	
	private Context context;
	private CalendarConfig config;
	public int currentMonth;
	public Activity parentActivity;
	private List<Calendar> calendars;
	public int selectedJulianDay = 0;
	
	public CalendarAdapter(Context context, CalendarConfig config) {
		this.context = context;
		this.config = config;
	}
	
	@Override
	public int getCount() {
		return MAX_POSITION;
	}

	@Override
	public Object getItem(int position) {
		return new Integer(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		WeekInMonthView view;
		if (convertView == null) {
			view = new WeekInMonthView(context);
		} else {
			view = (WeekInMonthView)convertView;
			//logger.info("View reused: " + view.mFirstJulianDay);
		}
	
		//view.setLayoutParams(layoutParams);
		int firstJulianDay = position2JulianDay(position, config);
		if (selectedJulianDay != 0 && selectedJulianDay >= firstJulianDay && selectedJulianDay < firstJulianDay+7) {
			view.changeWeek(firstJulianDay, selectedJulianDay, currentMonth, config);
		} else {
			view.changeWeek(firstJulianDay, 0, currentMonth, config);
		}

		//logger.info("getView: " + position + ":" + firstJulianDay);

		// Load events in separate thread
	    new Thread(new EventLoader(firstJulianDay, view)).start();
		
		return view;
	}

	@Override
	public int getViewTypeCount() {
		return 1;
	}
	
	@Override
	public int getItemViewType (int position) {
		return 0;
	}
	
	public void setParentActivity(Activity parentActivity) {
		this.parentActivity = parentActivity;
	}
	
	public void setCurrentMonth(int currentMonth) {
		this.currentMonth = currentMonth;
	}
	
	public void setConfig(CalendarConfig config) {
		this.config = config;
	}
	
	public int position2JulianDay(int position, CalendarConfig config) {
		// Zero Julian day is Monday
		return (position * 7) - 1 + config.weekStartDay;
	}
	
    private class EventLoader implements Runnable {
    	private int julianDay;
    	private WeekInMonthView view;
    	
    	public EventLoader(int julianDay, WeekInMonthView view) {
    		this.julianDay = julianDay;
    		this.view = view;
    	}
    	
		@Override
		public void run() {
    		final List<Instance> instances = loadEvents(view.getContext(), julianDay);
    		view.post(new Runnable() {
                public void run() {
                	view.setInstances(instances);
                }
            });
		}

	    /**
	     * Get events within the week
	     */
	    private List<Instance> loadEvents(Context context, int mFirstJulianDay) {
	        Time tmpTime = new Time();
	        tmpTime.setJulianDay(mFirstJulianDay);
	        long begin = tmpTime.normalize(true) - 1000;
	        tmpTime.setJulianDay(mFirstJulianDay + 7);
	        long end = tmpTime.normalize(true) + 1000;
	        
	        CPSyncUtil util = CPSyncUtil.getInstance();
	        if (calendars == null) {
	        	calendars = util.getCalendars(parentActivity, true);
	        }
	        
	        List<Instance> mInstances = util.getInstances(parentActivity, calendars, begin, end);
	        
	        /*
	        if (mInstances != null) {
	        	for (Instance instance: mInstances) {
	        		logger.info("Instance for " + mFirstJulianDay + ": " + instance);
	        	}
	        }
	        */
	        /*
	        StringBuffer eventsStr = new StringBuffer();
	        if (mInstances != null) {
	            for (Instance instance: mInstances) {
	            	eventsStr.append(instance.getEventId() + ":" + instance.getCalendarId() + ":" + instance.getTitle() + ":" + SimpleDateFormat.getDateTimeInstance().format(new Date(Long.valueOf(instance.getBegin()))) + ":" + SimpleDateFormat.getDateTimeInstance().format(Long.valueOf(instance.getEnd())));
	            	eventsStr.append("\n");
	            }
	            logger.info("Events=" + eventsStr);
	        }
	        */
	        
	        return mInstances;
	    }
    }
}
